package com.wit.witmg.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.wit.witmg.entity.*;
import com.wit.witmg.mapper.TProdInputMapper;
import com.wit.witmg.mapper.TProdstockMapper;
import com.wit.witmg.mapper.TProdtaskMapper;
import com.wit.witmg.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wit.witmg.util.ErrorCode;
import com.wit.witmg.util.JsonResult;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author bob
 * @since 2025-01-20
 */
@Service
@RequiredArgsConstructor
public class TProdInputServiceImpl extends ServiceImpl<TProdInputMapper, TProdInput> implements ITProdInputService {

    final ITProdstatService statService;
    final TProdstockMapper stockMapper;
    final TProdtaskMapper taskMapper;
    final ITProdFeeService feeService;
    final ITMatOutputService outputService;
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Object add(HttpServletRequest request, String json, Integer stat) {
       // 参数(json[pid,bn,inqt,indate,amount等字段],stat),根据pid联计划表t_prodTask查询amount，
        // 当stat为4时，把amount*本次入库数量inqt/预计整批数量pqt作为原材料成本；当stat为5时，把amount*（1-累计入库数量inqt/预计整批数量pqt)作为原材料成本，
        // 把生产计划表的实际完工时间edate改为入库时间indate；再把生产计划表的inqt+=inqt,把字段stat更新为参数stat；
        // 再根据pid联工序统计表t_prodStat查询，每条工序都生成一条制造费用表，把工序统计表的字段depr、rt、tldepr、ec、ep、pcwg分别*入库数量inqt保存到对应的同名字段中，
        // 并把金额（制造费用）累加到原材料成本中（作为入库金额），连同json参数中的其它字段增加到入库表中，同时根据bn把库存表的amount+=amount,qt+=inqt。
//        json="{\"oid\":14,\"pid\":19,\"bn\":\"6F.1.1.1.5.F1\",\"na\":\"阀片浆料\",\"guid\":10001,\"size\":\"F1\",\"remark\":\"\",\"unit\":\"kg\",\"inqt\":\"500\",\"indate\":\"2025-02-08 17:29:15\",\"store\":\"成品库\",\"space\":\"\"}";
        TProdInput t= JSON.parseObject(json, TProdInput.class);
        if(t==null || t.getPid()==null || stat==null){
            return JsonResult.error(ErrorCode.ERR_200);
        }
        double amount=0.0;
        //查询 计划表 获取材料成本
        TProdtask taskEnt = taskMapper.selectById(t.getPid());
        if(stat==4){
            amount=taskEnt.getAmount()*t.getInqt()/taskEnt.getPqt();
        }else{
            amount=taskEnt.getAmount()*(1-taskEnt.getInqt()/taskEnt.getPqt());
        }
        if(stat==5){
            if(!taskMapper.updateInqtEnd(t.getPid(),t.getInqt(),new Date())){
                return JsonResult.error(ErrorCode.ERR_504);
            }
        }else {
            if (!taskMapper.updateInqt(t.getPid(), t.getInqt(), stat)) {
                return JsonResult.error(ErrorCode.ERR_504);
            }
        }
        ArrayList<TProdFee> feeList=new ArrayList<>();
        QueryWrapper<TProdstat> qw= new QueryWrapper<>();
        qw.eq("pid", t.getPid());
        List<TProdstat> statList=statService.list(qw);
        for (TProdstat item : statList) {
            TProdFee fee=new TProdFee();
            BeanUtils.copyProperties(item, fee);
            fee.setIndate(t.getIndate());
            fee.setDepr(item.getDepr()*t.getInqt());
            fee.setRt(item.getRt()*t.getInqt());
            fee.setTldepr(item.getTldepr()*t.getInqt());
            fee.setEc(item.getEc()*t.getInqt());
            fee.setEp(item.getEp()*t.getInqt());
            fee.setPcwg(item.getPcwg()*t.getInqt());
            feeList.add(fee);
            amount+=fee.getDepr()+fee.getRt()+fee.getTldepr()+fee.getEc()+fee.getEp()+fee.getPcwg();
        }
        //增加一条入库表数据
        t.setAmount(amount);
        if(save(t)){
            //保存制造费用数据
            if(!feeList.isEmpty() && !feeService.saveBatch(feeList)){
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();//回滚
                return JsonResult.error(ErrorCode.ERR_504);
            }
            //同时根据bn把库存表的amount+=amount,qt+=inqt；
            int count= stockMapper.selectCount(new QueryWrapper<TProdstock>().eq("bn",t.getBn()));
            if(count==0){//首次入库要添加数据
                TProdstock stock=new TProdstock();
                BeanUtils.copyProperties(t, stock);
                stock.setAmount(t.getAmount());
                stock.setQt(t.getInqt());
                stock.setDate(new Date());
                if(stockMapper.insert(stock)>0){
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();//回滚
                    return JsonResult.error(ErrorCode.ERR_504);
                }
            }else {
                if(!stockMapper.updateAmount(t.getBn(),t.getAmount(),t.getInqt())){
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();//回滚
                    return JsonResult.error(ErrorCode.ERR_504);
                }
            }
        }
        return JsonResult.success(t);
    }
}
